package com.neusoft.neuiotms.dcam.workflow.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import javax.persistence.EntityNotFoundException;
import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;
import com.neusoft.bizcore.activiti.dto.ProcessInstanceDTO;
import com.neusoft.bizcore.activiti.service.ProcessInstanceService;
import com.neusoft.bizcore.activiti.service.WorkOrderService;
import com.neusoft.bizcore.auth.common.bean.UserBean;
import com.neusoft.bizcore.web.constant.ExceptionConstants;
import com.neusoft.bizcore.web.exception.UnitedException;
import com.neusoft.neuiotms.dcam.anhui.itsm.WorkflowBean;
import com.neusoft.neuiotms.dcam.constant.DCAMConsts;
import com.neusoft.neuiotms.dcam.fixed.dto.AssetLifeCycleDTO;
import com.neusoft.neuiotms.dcam.fixed.model.Asset;
import com.neusoft.neuiotms.dcam.fixed.repository.AssetRepository;
import com.neusoft.neuiotms.dcam.fixed.service.AssetLifeCycleService;
import com.neusoft.neuiotms.dcam.fixed.service.AssetService;
import com.neusoft.neuiotms.dcam.fixed.service.ItsmService;
import com.neusoft.neuiotms.dcam.workflow.converter.GenghuanAssetKJConverter;
import com.neusoft.neuiotms.dcam.workflow.converter.GenghuanKJConverter;
import com.neusoft.neuiotms.dcam.workflow.converter.ITSMApproveConverter;
import com.neusoft.neuiotms.dcam.workflow.dto.GenghuanItemKJDTO;
import com.neusoft.neuiotms.dcam.workflow.dto.GenghuanKJDTO;
import com.neusoft.neuiotms.dcam.workflow.dto.ITSMApproveDTO;
import com.neusoft.neuiotms.dcam.workflow.model.GenghuanAssetKJ;
import com.neusoft.neuiotms.dcam.workflow.model.GenghuanItemKJ;
import com.neusoft.neuiotms.dcam.workflow.model.GenghuanKJ;
import com.neusoft.neuiotms.dcam.workflow.model.ITSMApprove;
import com.neusoft.neuiotms.dcam.workflow.repository.GenghuanAssetKJRepository;
import com.neusoft.neuiotms.dcam.workflow.repository.GenghuanItemKJRepository;
import com.neusoft.neuiotms.dcam.workflow.repository.GenghuanKJRepository;
import com.neusoft.neuiotms.dcam.workflow.repository.ITSMApproveRepository;
import com.neusoft.neuiotms.dcam.workflow.service.GenghuanKJService;

import io.micrometer.core.instrument.util.StringUtils;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class GenghuanKJServiceImpl implements GenghuanKJService {

    @Autowired
    private WorkOrderService workOrderService;
    @Autowired
    private ProcessInstanceService processInstanceService;
    @Autowired
    private GenghuanKJRepository genghuanKJRepository;
    @Autowired
    private GenghuanItemKJRepository genghuanItemKJRepository;
    @Autowired
    private GenghuanKJConverter genghuanKJConverter;
    @Autowired
    private ITSMApproveRepository approveRepository;
    @Autowired
    private ITSMApproveConverter approveConverter;
    @Autowired
    private AssetRepository assetRepository;
    @Autowired
    private AssetService assetService;
    @Autowired
    private AssetLifeCycleService assetLifeCycleService;
    //    @Autowired
    //    private ItsmService itsmService;
    @Autowired
    private GenghuanAssetKJRepository genghuanAssetKJRepository;
    @Autowired
    private GenghuanAssetKJConverter genghuanAssetKJConverter;
    @Autowired
    private ItsmService itsmService;

    @Transactional
    @Override
    public GenghuanKJDTO create(final GenghuanKJDTO dto, final UserBean user) {

        final String taskId = dto.getTaskId();
        final ProcessInstanceDTO instance =
                this.workOrderService.submit(dto.getTitle(), DCAMConsts.PROCESSS_GENGHUAN_KJ_KEY, dto.getWorkOrderNum(),
                        user);
        dto.setTaskId(instance.getTaskId());
        dto.setWorkOrderNum(instance.getWorkorderNum());
        dto.setCreateUser(user.getUsername());
        dto.setCreateUserName(user.getName());

        // 查询当前workOrderNum和TaskId下是否存在记录
        final GenghuanKJ oldModel = this.genghuanKJRepository.findByWorkOrderNumAndTaskId(
                dto.getWorkOrderNum(), taskId);
        if (oldModel == null) {
            dto.setId(null);
        }

        // 解锁以前的资产信息
        final List<GenghuanItemKJ> all = this.genghuanItemKJRepository.findByMain_WorkOrderNum(dto.getWorkOrderNum());
        if (null != all) {
            this.assetService.updateLocked(all.stream().map(l -> l.getCode()).distinct().collect(Collectors.toList()),
                    false);
        }

        GenghuanKJ model = this.genghuanKJConverter.toModel(dto);
        model = this.genghuanKJRepository.save(model);

        // 完成当前节点
        this.processInstanceService.complete(dto.getWorkOrderNum(), dto.getTaskId(), user);

        final GenghuanKJDTO result = this.genghuanKJConverter.toDTO(model);

        // 枷锁资产信息
        this.assetService.updateLocked(
                result.getDetails().stream().map(l -> l.getCode()).distinct().collect(Collectors.toList()),
                true);

        return result;
    }

    @Override
    public GenghuanKJDTO detail(final String workOrderNum, final String taskId, final UserBean user) {
        GenghuanKJ model = null;
        try {
            if (StringUtils.isNotBlank(workOrderNum) && !"NULL".equals(taskId)) {
                model = this.genghuanKJRepository.findByWorkOrderNumAndTaskId(workOrderNum, taskId);
                if (model == null) {
                    // 获取前一节点的TaskID
                    final String lastTaskId = this.processInstanceService.getLastTaskId(taskId, user);
                    if (lastTaskId == null) {
                        return new GenghuanKJDTO();
                    } else {
                        model = this.genghuanKJRepository.findByWorkOrderNumAndTaskId(workOrderNum,
                                lastTaskId);
                    }
                }
            } else if ("NULL".equals(taskId)) {
                model =
                        this.genghuanKJRepository.findTopByWorkOrderNumOrderByCreateTimeDesc(workOrderNum);
            }
        } catch (final EntityNotFoundException e) {
            throw new UnitedException(ExceptionConstants.ENTITY_NOT_FOUND,
                    new Object[] {workOrderNum },
                    new Object[] {taskId });
        }
        return this.genghuanKJConverter.toDTO(model);
    }

    @Transactional
    @Override
    public ITSMApproveDTO itsmCreate(final ITSMApproveDTO dto, final UserBean user) {

        final ITSMApprove model = this.approveConverter.toModel(dto);
        this.approveRepository.save(model);
        this.processInstanceService.setGlobalVariable(dto.getTaskId(), DCAMConsts.PROCESSS_GENGHUAN_KJ_APPROVE_RESULT,
                dto.getResult());
        // 完成当前节点
        this.processInstanceService.complete(dto.getWorkOrderNum(), dto.getTaskId(), user);

        return this.approveConverter.toDTO(model);
    }

    @Override
    public ITSMApproveDTO itsmDetails(final String workOrderNum, final String taskId, final UserBean user) {
        ITSMApprove model = null;
        try {
            if (StringUtils.isNotBlank(workOrderNum) && !"NULL".equals(taskId)) {
                model = this.approveRepository.findByWorkOrderNumAndTaskId(workOrderNum, taskId);
                if (model == null) {
                    // 获取前一节点的TaskID
                    final String lastTaskId = this.processInstanceService.getLastTaskId(taskId, user);
                    if (lastTaskId == null) {
                        return new ITSMApproveDTO();
                    } else {
                        model = this.approveRepository.findByWorkOrderNumAndTaskId(workOrderNum,
                                lastTaskId);
                    }
                }
            } else if ("NULL".equals(taskId)) {
                model =
                        this.approveRepository.findTopByWorkOrderNumOrderByCreateTimeDesc(workOrderNum);
            }
        } catch (final EntityNotFoundException e) {
            throw new UnitedException(ExceptionConstants.ENTITY_NOT_FOUND,
                    new Object[] {workOrderNum },
                    new Object[] {taskId });
        }
        return this.approveConverter.toDTO(model);
    }

    @Transactional
    @Override
    public GenghuanKJDTO confrimCreate(final GenghuanKJDTO dto, final UserBean user) {

        List<GenghuanAssetKJ> models = dto.getAssets().stream().map(s -> this.genghuanAssetKJConverter.toModel(s))
                .collect(Collectors.toList());
        models = this.genghuanAssetKJRepository.saveAll(models);

        // 更新存放仓库位置信息
        dto.getDetails().forEach(l -> {
            final GenghuanItemKJ item = this.genghuanItemKJRepository.getOne(l.getId());
            item.setGenghuanLocation(l.getGenghuanLocation());
            item.setGenghuanLocationName(l.getGenghuanLocationName());
            this.genghuanItemKJRepository.save(item);
        });

        // 完成当前节点信息
        this.processInstanceService.complete(dto.getWorkOrderNum(), dto.getTaskId(), user);

        try {
            // 对接ITSM
            final List<WorkflowBean.AssetBean> assetList = Lists.newArrayList();
            for (final GenghuanItemKJDTO item : dto.getDetails()) {
                final WorkflowBean.AssetBean assetBean = WorkflowBean.AssetBean.builder()
                        .assetId(item.getCode())
                        .assetClassID(item.getSmallTypeCode())
                        .assetModel(item.getSpecifications())
                        .assetUnit("未知")
                        .assetPrice(0)
                        .assetNumber(1)
                        .assetName(item.getName())
                        .assetType("1")
                        .assetSign("未知")
                        .build();
                assetList.add(assetBean);
            }

            final WorkflowBean workflowBean = WorkflowBean.builder()
                    .workNum(dto.getWorkOrderNum())
                    .workName("设备更换")
                    .workType("70")
                    .workContent("设备更换申请")
                    .applyUser(dto.getCreateUser())
                    .assetList(assetList)
                    .build();

            this.itsmService.pushItsm(workflowBean);
        } catch (final Exception e) {
            GenghuanKJServiceImpl.log.error("设备更换流程推送ITSM时发生错误", e);
        }

        return dto;
    }

    @Override
    public GenghuanKJDTO confrimDetail(final String workOrderNum, final String taskId, final UserBean user) {
        final GenghuanKJ model = this.genghuanKJRepository.findTopByWorkOrderNumOrderByCreateTimeDesc(workOrderNum);
        final GenghuanKJDTO dto = this.genghuanKJConverter.toDTO(model);
        final List<GenghuanAssetKJ> assets =
                this.genghuanAssetKJRepository.findByWorkOrderNumAndTaskId(workOrderNum, taskId);
        assets.stream().map(s -> this.genghuanAssetKJConverter.toDTO(s)).forEach(dto.getAssets()::add);
        return dto;
    }

    @Transactional
    @Override
    public ITSMApproveDTO confirm(final ITSMApproveDTO dto, final UserBean user) {
        // 完成当前节点
        this.processInstanceService.complete(dto.getWorkOrderNum(), dto.getTaskId(), user);
        this.updateAssets(dto.getWorkOrderNum());
        return dto;
    }

    private void updateAssets(final String workOrderNum) {
        final List<AssetLifeCycleDTO> lifeList = new ArrayList<>();
        final List<Asset> assets = new ArrayList<>();
        final GenghuanKJ model = this.genghuanKJRepository.findTopByWorkOrderNumOrderByCreateTimeDesc(workOrderNum);

        // 恢复在库 更改状态闲置
        model.getDetails().stream().map(a -> {
            final Asset asset = this.assetRepository.findByCode(a.getCode());
            asset.setStatus(DCAMConsts.ASSET_STATUS_UNUSED);
            asset.setLocation(a.getGenghuanLocation());
            asset.setLocationName(a.getGenghuanLocationName());
            asset.setManagementOrgName(null);
            asset.setManagementOrgCode(null);
            asset.setManagementUserCode(null);
            asset.setManagementUserName(null);
            asset.setLocked(false);

            // 生命周期
            lifeList.add(AssetLifeCycleDTO.builder().code(asset.getCode())
                    .lifeCycle(DCAMConsts.ASSET_LIFE_TYPE_GENGHUAN)
                    .content(asset.getName() + "已更换退库").workNum(workOrderNum).build());
            return asset;
        }).forEach(assets::add);

        final List<GenghuanAssetKJ> genghuanAssets = this.genghuanAssetKJRepository.findByWorkOrderNum(workOrderNum);

        genghuanAssets.stream().map(a -> {
            final Asset asset = this.assetRepository.findByCode(a.getCode());
            asset.setStatus(DCAMConsts.ASSET_STATUS_USED);
            asset.setManagementUserCode(model.getCreateUser());
            asset.setManagementUserName(model.getCreateUserName());
            asset.setLocked(false);

            // 生命周期
            lifeList.add(AssetLifeCycleDTO.builder().code(asset.getCode())
                    .lifeCycle(DCAMConsts.ASSET_LIFE_TYPE_GENGHUAN)
                    .content(asset.getName() + "已更换领用").workNum(workOrderNum).build());
            return asset;
        }).forEach(assets::add);

        if ((assets != null) && (assets.size() > 0)) {
            this.assetRepository.saveAll(assets);
        }

        if (lifeList.size() > 0) {
            this.assetLifeCycleService.batchCreate(lifeList);
        }
    }
}
